import $store from '@/store/index.js';
import sqliteFriend from './friend.js'
import sqliteGroup from './group.js'
import friendsApi from "@/services/api/friends.js"
import groupApi from "@/services/api/group.js"
import msgApi from "@/services/api/msg.js"
const syczuanNotice = uni.requireNativePlugin("syczuan-notice");
export default {
	/* 操作新消息 */
	newMsg(msgArray,isnotik) {
		return new Promise(async (resolve, reject) => {
			//发送者的id
			let myid = $store.state.user.user_info.user_id
			//当前聊天的人的id
			const activeChatUuid = $store.state.chat.chatInfo && $store.state.chat.chatInfo.uuid || ''; // 访问根级状态的chatInfo
			// 如果传递的是单个消息，将其转为数组
			if (!Array.isArray(msgArray)) {
				msgArray = [msgArray];
			}
			let atme = 0
			let lastMessage = msgArray[msgArray.length - 1];
			let chat_id = lastMessage.chat_type == 'group'?lastMessage.target_id:lastMessage.sender_id == myid ? lastMessage.target_id : lastMessage.sender_id
			if(lastMessage.chat_type == 'group' && activeChatUuid != chat_id){
				//不是自己发的并且
				let atSerchArr = msgArray.filter(msg => msg.msg_type == 'text' && msg.sender_id != myid)
				let isat = atSerchArr.some((message)=> {
					return this.checkMention(message.content_text[0].text.content,myid)
				});
				if(isat){
					atme = 1
				}
			}
			console.log('11111111111');
			try {
				let sessionItem = await $store.state.user.sqlite.session.where({
					field: 'chat_id',
					val: `'${chat_id}'`
				}).first()
				let unreadCount = 0;
				let sessionData = {}
				//如果找的到那么异步更新会话和添加消息
				if (sessionItem) {
					// 计算未读数
					unreadCount = msgArray.filter(msg => msg.sender_id != myid).length;
					sessionData = {
						...sessionItem,
						chat_id: chat_id,
						conversation_id:lastMessage.conversation_id || 0,
						last_msg_id: lastMessage.msg_id,
						last_time: lastMessage.create_time.toString().length == 10?lastMessage.create_time*1000:lastMessage.create_time,
						last_msg_type: lastMessage.msg_type,
						last_msg: JSON.stringify(lastMessage.content_text),
						at:atme,
					}
					console.log('2222111111',sessionData,'-',unreadCount);
					await $store.dispatch('handleNewMessage', {
						chat_id: chat_id,
						data: sessionData,
						unreadCount: unreadCount // 传递累加的未读数
					})
				} else {
					//获取用户信息
					let chatinfo = null
					if(lastMessage.chat_type == 'private'){
						let res = await sqliteFriend.getUserInfo(chat_id)
						if (res && res.user_type) {
							chatinfo = res
						}else{
							//网络请求并更新用户表
							let apires = await friendsApi.getFriendInfo(chat_id)
							if(apires){
								chatinfo = apires
							}
						}
						sessionData.chat_member_type = chatinfo.user_type || ''
						sessionData.chat_name = chatinfo.friend_remark || chatinfo.nick_name
						sessionData.nick_name = chatinfo.nick_name
					}else if(lastMessage.chat_type == 'group'){
						let res = await sqliteGroup.getGroupInfo(chat_id)
						if (res) {
							chatinfo = res
						}else{
							//网络请求并更新群信息
							let apires = await groupApi.getGroupInfo(chat_id)
							if(apires){
								chatinfo = apires
							}
						}
						sessionData.chat_member_type = ''
						sessionData.chat_name = chatinfo.group_name
						sessionData.nick_name = chatinfo.group_name
						sessionData.tags = chatinfo.tags || ''
						sessionData.tags_font_color = chatinfo.tags_font_color || ''
					}
					 
					//如果没有找到那么同步执行插入回话和添加消息
					sessionData = {
						...sessionData,
						chat_id: chat_id,
						conversation_id:lastMessage.conversation_id || 0,
						chat_face: chatinfo.avatar_url,
						chat_type: lastMessage.chat_type,
						last_msg_id: lastMessage.msg_id,
						last_time: lastMessage.create_time.toString().length == 10?lastMessage.create_time*1000:lastMessage.create_time,
						disturbing: chatinfo.disturbing || 0,
						last_msg_type: lastMessage.msg_type,
						last_msg: JSON.stringify(lastMessage.content_text),
						at:atme,
					}
					
					// 计算未读数
					unreadCount = msgArray.filter(msg => msg.sender_id != myid).length;
					console.log('2222333333',sessionData,'-',unreadCount);
					//更新会话
					await $store.dispatch('handleNewMessage', {
						chat_id: chat_id,
						data: sessionData,
						unreadCount: unreadCount // 传递累加的未读数
					})
				}
				
				
				// 批量插入消息
				let msgDataArray = msgArray.map(data => ({
					msg_id: data.msg_id,
					local_id: data.local_id,
					sender_id: data.sender_id,
					conversation_id: data.conversation_id || 0,
					msg_type: data.msg_type,
					content_text: JSON.stringify(data.content_text),
					target_id: data.target_id,
					ref_msg_id:data.ref_msg_id || '',
					create_time: data.create_time,
					chat_type: data.chat_type,
					ip:data.ip ||'',
					ip_addr:data.ip_addr || '',
					is_review:data.is_review == 0 ? data.is_review : 1,
					msg_status: data.msg_status
				}));
				console.log('3333333333',msgDataArray);
				await $store.state.user.sqlite.message.batchInsert(msgDataArray)
				
				//是否通知页面执行操作，目前是主动发送的不用通知，被动接收的都得通知
				console.log('44444',msgArray);
				if(isnotik){
					//证明当前正在和此人聊天
					if(activeChatUuid == chat_id){
						uni.$emit('onMessage', msgArray)
					}
				}
				
				let notif = myid+'notif'
				let notifsStorage = uni.getStorageSync(notif)
				if(notifsStorage){
					notifsStorage = JSON.parse(notifsStorage)
				}
				if(!uni.$appShow && lastMessage.sender_id != myid && !sessionData.disturbing && !notifsStorage.disturb  && !notifsStorage.stopNewMsg){ 
					this.linePush(sessionData,notifsStorage)
				}else if(uni.$appShow && activeChatUuid != chat_id && lastMessage.sender_id != myid && !sessionData.disturbing && !notifsStorage.disturb){
					//是否关闭了声音判断
					if(!notifsStorage.stopAudio){
						uni.$u.throttle(()=>{
							const audio = uni.createInnerAudioContext();
							audio.src = "/static/preview.mp3";
							audio.play();
						}, 500,true)
					}
					//是否关闭了震动判断
					if(!notifsStorage.stopVibration){
						plus.device.vibrate()
					}
					if(activeChatUuid == '' && uni.$u.page() !== "/pages/start/index"){
						this.notify(sessionData,notifsStorage)
					}
				}
				resolve()
			} catch (e) {
				console.log(e);
				reject(e)
			}

		})
	},
	//在线后台推送
	linePush(sessionData,notifsStorage){
		if(notifsStorage.stopNewMsg)return
		// 发送通知
		 syczuanNotice.send(
		   {
			 noticeId:sessionData.conversation_id,
			 // 通知标题
			 title: sessionData.chat_name,
			 // 通知内容
			 content: notifsStorage.stopMsgDel?sessionData.chat_name+getApp().$t("index.index.sendAmessage") : this.msgDetails(sessionData.last_msg_type,sessionData.last_msg),
			 // 大图标
			 largeIcon: false,
			 // 点击是否自动关闭通知
			 autoCancel: true,
			 // 毫秒时间戳 默认显示当前时间
			 noticeTime: true,
			 // 通知优先级
			 import: 0,
			 // 未读通知数 0不显示
			 badge: 0,
			 // 通知长文本
			 bigText: "",
			 // 自定义数据
			 payload: {
			   data:sessionData
			 },
		   },
		   (e) => {
			 console.log(e);
		   }
		 );
	},
	notify(sessionData,notifsStorage){
		if(notifsStorage.stopNewMsg)return
		let params = {
			messageTitle: sessionData.chat_name,
			messageContent: notifsStorage.stopMsgDel?sessionData.chat_name+getApp().$t("index.index.sendAmessage") : this.msgDetails(sessionData.last_msg_type,sessionData.last_msg),
			messageImage: sessionData.chat_face,
			click: function(){
				if (sessionData.chat_type == 'private') {
					uni.$Router.push({
						name: 'chatMsg',
						params: {
							friend_idx:sessionData.chat_id,
							nick_name:sessionData.chat_name,
							avatar_url:sessionData.chat_face,
							screen: uni.$u.page() !== "/pages/index/index" && true || ''
						}
					});
				} else {
					uni.$Router.push({
						name: 'chatGroupMsg',
						params: {
							group_id:sessionData.chat_id,
							group_name:sessionData.chat_name,
							avatar_url:sessionData.chat_face,
							screen:uni.$u.page() !== "/pages/index/index" && true || ''
						}
					});
				}
			}
		}
		uni.$appPush(params)
	},
	//判断一下是否@了我
	checkMention(message, myid) {
	    // 正则表达式来匹配消息中的{}部分，提取用户名和标识号
	    // var regex = /\{([^:]+):(\d+)\}/g;
		var regex = /\{([^:]+):([^}]+)\}/g;
	    var match;
	    
	    while ((match = regex.exec(message)) !== null) {
	        var username = match[1]; // 获取花括号内的用户名
	        var identifier = match[2]; // 获取花括号内的标识号
	        // 判断标识号是否匹配
	        if (identifier == myid || identifier == 'all') {
	            return 1
	        }
	    }
	    // 如果未找到匹配的@提及
	    return 0
	},
	msgDetails(msg_type,last_msg) {
		switch (msg_type){
			case 'text':
				const parsedContent = JSON.parse(last_msg)?.[0]?.text?.content;
				const content = parsedContent !== undefined ? parsedContent : last_msg;
				return  this.convertToAtFormat(content)
				break;
			case 'image':
				return `[${getApp().$t('chat.msg.type.image')}]`
				break;
			case 'video':
				return `[${getApp().$t('chat.msg.type.video')}]`
				break;
			case 'audio':
				return `[${getApp().$t('chat.msg.type.audio')}]`
				break;
			case 'r_p':
				return `[${getApp().$t('chat.msg.type.r_p')}]`
				break;
			case 'd_r':
				return `[${getApp().$t('chat.msg.type.dice')}]`
				break;
			case 'video_call':
				return `[${getApp().$t('chat.msg.type.videoCall')}]`
				break;
			case 'voice_call':
				return `[${getApp().$t('chat.msg.type.voiceCall')}]`
				break;
			case 'b_c':
				return `[${getApp().$t('chat.msg.type.b_c')}]`
				break;
			case 'mixed':
				return `[${getApp().$t('chat.msg.type.mixed')}]`
				break;
			case 'sys_notice':
				const sysparsedContent = JSON.parse(last_msg)?.[0]?.text?.content;
				return sysparsedContent !== undefined ? sysparsedContent : last_msg;
				break;
			default:
				break;
		}
	},
	convertToAtFormat(input) {
	    // 使用正则表达式匹配并替换字符串
	    const regex = /{([^:]+):([^}]+)}/g; // 匹配形如 {内容1:内容2} 的模式
	    const result = input.replace(regex, '@$1 '); // 替换为 @内容1
	
	    return result;
	},
	//清空聊天记录
	async clearChatHistory(chat_id,chat_type){
		await this.delMsgUserId(chat_id,chat_type)
		//这里只需要更新会话表
		$store.dispatch('updateSession',{
			chat_id: chat_id,
			data: {
				last_msg: '',
				last_msg_id:'',
				last_time:'',
				last_msg_type:'',
				unread_count:0
			}
		})
		const activeChatUuid = $store.state.chat.chatInfo && $store.state.chat.chatInfo.uuid || ''; // 访问根级状态的chatInfo
		if(chat_id == activeChatUuid){
			uni.$emit('onMessageControls', {
				type:'clearChat'
			})
		}
		uni.showToast({
			title:getApp().$t("tost.title.cleanOk"),
			icon:'none'
		})
	},
	
	//清空所有聊天记录
	async clearChatAllHistory(){
		await $store.state.user.sqlite.message.delete()
		await $store.state.user.sqlite.session.delete()
		//清空会话
		$store.commit('setSeesion', []);
		uni.showToast({
			title:getApp().$t("tost.title.cleanOk"),
			icon:'none'
		})
	},
	
	//操作消息回执,initiative为true=api主动发送,否则是来了新消息发送回执
	async receipt(data,initiative = true){
		let sql = ''
		let upsql = null
		let myid = $store.state.user.user_info.user_id
		if(data.chat_type == 'private'){
			sql = `SELECT * FROM messages WHERE chat_type = '${data.chat_type}' AND (target_id = '${myid}' AND sender_id = '${data.uuid}') AND msg_status='unread' ORDER BY msg_id desc LIMIT 1`
			upsql = (msg_id)=>{
				return `UPDATE messages SET msg_status='read' WHERE chat_type = '${data.chat_type}' AND (target_id = '${myid}' AND sender_id = '${data.uuid}') AND msg_id <= '${msg_id}' AND msg_status = 'unread'`
			}
		}else if(data.chat_type == 'group'){
			sql = `SELECT * FROM messages WHERE chat_type = '${data.chat_type}' AND (target_id = '${data.uuid}' AND sender_id != '${myid}') AND msg_status='unread' ORDER BY msg_id desc LIMIT 1`
			upsql = (msg_id)=>{
				return `UPDATE messages SET msg_status='read' WHERE chat_type = '${data.chat_type}' AND (target_id = '${data.uuid}' AND sender_id != '${myid}') AND msg_id <= '${msg_id}' AND msg_status = 'unread'`
			}
		}
		try{
			//页面调用主动发送的回执
			if(initiative){
				let sqlval = await $store.state.user.sqlite.message.selectSql(sql)
				if(sqlval[0]){
					let apires = await msgApi.receipt(sqlval[0].conversation_id,sqlval[0].msg_id,data.uuid,data.chat_type)
					if(apires){
						let endsql = upsql && upsql(sqlval[0].msg_id) || ''
						if(endsql){
							await $store.state.user.sqlite.message.executeSql(endsql)
							return sqlval[0].msg_id
						}
					}
				}
			}else{
				//socket推送告知发送回执
				let apires = await msgApi.receipt(data.conversation_id,data.msg_id,data.uuid,data.chat_type)
				if(apires){
					let endsql = upsql && upsql(data.msg_id) || ''
					if(endsql){
						await $store.state.user.sqlite.message.executeSql(endsql)
						return data.msg_id
					}
				}
			}
			return false
		}catch(error){
			throw error;
		}
	},
	
	//获取会话离线消息
	getMessageOffline(select_type = '1') {
		try {
			let sessionList = $store.state.session.sessionList
			//拉取离线
			for (let i = 0; i < sessionList.length; i ++) {
				let item = sessionList[i]
					msgApi.messageOffline({
						target_id:item.chat_id,
						msg_id:item.last_msg_id || "0",
						select_type
					},item.chat_type)
			}
		} catch (e) {
			throw e;
		}
	},
	
	//获取聊天信息
	getMsgList(data, pages) {
		let sql = ''
		if(data.chat_type == 'private'){
			let myid = $store.state.user.user_info.user_id
			sql = `SELECT * FROM messages WHERE chat_type = '${data.chat_type}' AND ((target_id = '${data.uuid}' AND sender_id = '${myid}') OR (target_id = '${myid}' AND sender_id = '${data.uuid}')) ORDER BY id desc LIMIT ${pages.pageSize} OFFSET ${pages.offset}`
		}else if(data.chat_type == 'group'){
			sql = `SELECT * FROM messages WHERE chat_type = '${data.chat_type}' AND target_id = '${data.uuid}' ORDER BY id desc LIMIT ${pages.pageSize} OFFSET ${pages.offset}`
		}
		console.log(sql);
		return $store.state.user.sqlite.message.selectSql(sql)
	},
	
	//获取聊天分类信息
	getMsgSortList(data, pages) {
		let sql = ''
		let searchWhere = ''
		if(data.search){
			searchWhere = `AND content_text LIKE '%${data.search}%'`
		}
		let msgTypeWhere = '';
		if (data.msg_type) {
		  if (Array.isArray(data.msg_type)) {
		    // 如果是数组，转换成逗号分隔的字符串列表
			let msgTypes = data.msg_type.map(type => `'${type}'`).join(', ');
		    msgTypeWhere = `AND msg_type IN (${msgTypes})`  
		  } else {
		    // 如果是单个字符串，直接使用
		    let msgTypes = `'${data.msg_type}'`;
			msgTypeWhere = `AND msg_type IN (${msgTypes})`  
		  }
		}
		if(data.chat_type == 'private'){
			let myid = $store.state.user.user_info.user_id
			sql = `SELECT * FROM messages WHERE chat_type = '${data.chat_type}' ${msgTypeWhere} AND ((target_id = '${data.uuid}' AND sender_id = '${myid}') OR (target_id = '${myid}' AND sender_id = '${data.uuid}')) ${searchWhere} ORDER BY id desc LIMIT ${pages.pageSize} OFFSET ${pages.offset}`
		}else if(data.chat_type == 'group'){
			sql = `SELECT * FROM messages WHERE chat_type = '${data.chat_type}' ${msgTypeWhere} AND target_id = '${data.uuid}' ${searchWhere}  ORDER BY id desc LIMIT ${pages.pageSize} OFFSET ${pages.offset}`
		}
		console.log(sql);
		return $store.state.user.sqlite.message.selectSql(sql)
	},
	//根据msg_id获取消息
	getMsgIdItem(msg_id) {
		return new Promise((resolve, reject) => {
			$store.state.user.sqlite.message.where({ field: 'msg_id', val: `'${msg_id}'` }).first()
				.then(results => {
					resolve(results)
				})
				.catch(error => {
					reject(error)
				});
		})
	},
	
	
	//获取聊天信息的最后一条
	getLastMsg(data) {
		let sql = ''
		if(data.chat_type == 'private'){
			let myid = $store.state.user.user_info.user_id
			sql = `SELECT * FROM messages WHERE chat_type = '${data.chat_type}' AND ((target_id = '${data.uuid}' AND sender_id = '${myid}') OR (target_id = '${myid}' AND sender_id = '${data.uuid}')) ORDER BY id desc LIMIT 1`
		}else if(data.chat_type == 'group'){
			sql = `SELECT * FROM messages WHERE chat_type = '${data.chat_type}' AND target_id = '${data.uuid}' ORDER BY id desc LIMIT 1`
		}
		return $store.state.user.sqlite.message.selectSql(sql)
	},
	
	//通过msgID删除消息，如果为数组则是批量删除
	delMsg(msg_id,chat_type) {
		let delmsg_id = ''
		let opt = "="
		if (Array.isArray(msg_id)) {
			let msgIds = msg_id.map(v => `'${v}'`).join(',')
		    delmsg_id = `(${msgIds})`;
			opt = "in"
		} else {
		    delmsg_id = `'${msg_id}'`
		}
		return $store.state.user.sqlite.message.where([{
			field: 'msg_id',
			opt:opt,
			val: `${delmsg_id}`,
			logic: 'AND'
		},{
			field: 'chat_type',
			val: `'${chat_type}'`,
			logic: 'AND'
		}]).delete();
	},
	//通过用户id删除
	delMsgUserId(target_id,chat_type) {
		let sql = ''
		if(chat_type == 'private'){
			let myid = $store.state.user.user_info.user_id
			sql = `DELETE FROM messages WHERE chat_type = '${chat_type}' AND ((target_id = '${target_id}' AND sender_id = '${myid}') OR (target_id = '${myid}' AND sender_id = '${target_id}'))`
			return $store.state.user.sqlite.message.executeSql(sql)
		}else if(chat_type == 'group'){
			sql = `DELETE FROM messages WHERE chat_type = '${chat_type}' AND target_id = '${target_id}'`
			return $store.state.user.sqlite.message.executeSql(sql);
		}
	},
	//添加或修改消息
	addOrEditMsg(data) {
		return $store.state.user.sqlite.message.replace(data)
	},
	//更新发送中为发送失败
	editSendState() {
		return $store.state.user.sqlite.message.where({ field: 'msg_status', val: `'lodding'`}).update({
			'msg_status':'failed'
		})
	},
	
	//更新已读回执，也就是小于这个msd_id的回执全部改为已读
	updateReceiptMessage({chat_type,sender_id,target_id,msg_id}) {
		  let sql = ''
		  let myid = $store.state.user.user_info.user_id
		  if(chat_type == 'private'){
			  //修改对方的消息
			sql = `UPDATE messages SET msg_status='read' WHERE chat_type = '${chat_type}' AND (target_id = '${sender_id}' AND sender_id = '${target_id}') AND msg_id <= '${msg_id}' AND msg_status = 'unread'`
		  }else if(chat_type == 'group'){
			let upid = `sender_id == '${myid}'`
			if(sender_id == myid){
			  	upid = 	`sender_id != '${myid}'`	  
			}
			sql = `UPDATE messages SET msg_status='read' WHERE chat_type = '${chat_type}' AND (target_id = '${target_id}' AND ${upid}) AND msg_id <= '${msg_id}' AND msg_status = 'unread'`
		  }
		  return $store.state.user.sqlite.message.executeSql(sql)
	},
	
	//更新聊天信息
	async updateMessageById(msg_id, updatedData) {
	  try {
	    await $store.state.user.sqlite.message.where({
			field: 'msg_id',
			val: `'${msg_id}'`
		}).update(updatedData);
		console.error('更新消息成功');
	    return true;
	  } catch (error) {
		  console.error(error);
	    throw error;
	  }
	},
}